package hn.sigit.view.workflow.transaction;

import hn.sigit.logic.ladmshadow.Util;
import hn.sigit.model.hnd.ladmshadow.Party;
import hn.sigit.model.hnd.ladmshadow.RRR;
import hn.sigit.model.hnd.ladmshadow.dao.PartyDAO;
import hn.sigit.model.ladm.external.ExtParty;
import hn.sigit.model.ladm.party.LA_Party;
import hn.sigit.model.ladm.party.dao.LA_PartyDAO;
import hn.sigit.model.ladm.special.Rational;
import hn.sigit.view.ShareValue;

public abstract class ParcelRRR {
	private boolean isSelected;
	private boolean newRRR = false;
	private ExtParty extParty;
	private ShareValue share;
	protected long presentationId;
	protected RRR rrr;
	
	public ParcelRRR(long presentationId, ExtParty extParty) {
		this.presentationId = presentationId;
		this.extParty = extParty;
		this.share = new ShareValue();
	}
	public ParcelRRR(long presentationId, ExtParty extParty, ShareValue share) {
		this.presentationId = presentationId;
		this.extParty = extParty;
		this.share = share;
	}
	
	public abstract Object getRrrType();
	public abstract String getTypeString();

	
	public boolean isSelected() {
		return isSelected;
	}
	public void setSelected(boolean isSelected) {
		this.isSelected = isSelected;
	}
	
	public boolean isNewRRR() {
		return newRRR;
	}
	public void setNewRRR(boolean newRRR) {
		this.newRRR = newRRR;
	}
	
	public ExtParty getExtParty() {
		return extParty;
	}
	public void setExtParty(ExtParty extParty) {
		this.extParty = extParty;
	}
	
	
	public ShareValue getShare() {
		return share;
	}
	public void setShare(ShareValue share) {
		this.share = share;
	}
	
	public long getPresentationId() {
		return presentationId;
	}
	public void setPresentationId(long presentationId) {
		this.presentationId = presentationId;
	}
	
	public String getOwner() {
		if (extParty != null)
			return extParty.getName();
		return "";
	}

	public String getShareString() {
		return share.toString();
	}
	
	public RRR getRrr() {
		return rrr;
	}
	
	protected void cancelChanges() {
		if (rrr == null) return;
		
		Rational rrrShare = rrr.getShare();
		if (rrrShare != null) {
			share.setNumerator(rrrShare.getNumerator());
			share.setDenominator(rrrShare.getDenominator());
		}
		else {
			share.setNumerator(0);
			share.setDenominator(0);
		}
		
		Party rrrParty = rrr.getParty();
		if (rrrParty != null && rrrParty.getExtParty() != null)
			extParty = rrrParty.getExtParty();
	}
	
	protected void applyChanges() {
		if (rrr == null) return;
		
		rrr.setShare(share.asLadmRational());
		
		if (rrr.getParty() == null || rrr.getParty().getExtParty() != extParty) {
			LA_Party laParty = LA_PartyDAO.loadPartyByExtParty(extParty);
			Party party = Util.LA_PartyToParty(laParty, presentationId, false, false);
			PartyDAO.save(party);
			
			rrr.setParty(party);
		}
		//else: do not to mark any changes
	}
}
